<template>
  <div
    ref="chartRef"
    :style="{ width: chartWidth, height: chartHeight }"
    class="pie-chart"
  ></div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      series: [
        { name: '产品A', value: 335 },
        { name: '产品B', value: 310 },
        { name: '产品C', value: 234 },
        { name: '产品D', value: 135 },
        { name: '产品E', value: 1548 }
      ]
    })
  },
  title: {
    type: String,
    default: '饼图'
  },
  width: {
    type: String,
    default: '400px'
  },
  height: {
    type: String,
    default: '300px'
  }
})

const chartRef = ref(null)
const chartInstance = ref(null)

const chartWidth = ref(props.width)
const chartHeight = ref(props.height)

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance.value = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return

  const option = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: '30px',
      left: 'center',
      data: props.data.series?.map(item => item.name) || []
    },
    series: [
      {
        name: props.title,
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: props.data.series || []
      }
    ]
  }

  chartInstance.value.setOption(option)
}

// 监听数据变化
watch(() => props.data, () => {
  updateChart()
}, { deep: true })

watch(() => props.title, () => {
  updateChart()
})

// 监听尺寸变化
watch(() => props.width, (newVal) => {
  chartWidth.value = newVal
  nextTick(() => {
    chartInstance.value?.resize()
  })
})

watch(() => props.height, (newVal) => {
  chartHeight.value = newVal
  nextTick(() => {
    chartInstance.value?.resize()
  })
})

onMounted(() => {
  initChart()
})
</script>

<style lang="scss" scoped>
.pie-chart {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}
</style>
